<?php
namespace app\common\service\store;

use app\admin\model\store\GoodsSpecifica;

/**
 * 规格
 * Class SpeciService
 * @package app\common\service\store
 */
class SpeciService
{
    /**
     * 规格添加
     * @param $post
     * @return GoodsSpecifica|\think\Model
     */
    public static function speciSave($post)
    {
        $rule['specifica_name'] = $post['specifica_name'];
        foreach ($post['specifica_value'] as $v) {
            $rule['specifica_value'][$v['value']] = $v['detail'];
        }
        $rule['specifica_value'] = json_encode($rule['specifica_value']);

        $data = GoodsSpecifica::create($rule);
        return $data;
    }

    /**
     * 规格列表
     * @param $page
     * @param $limit
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function speciList($page, $limit, $where)
    {
        $count = GoodsSpecifica::
        where($where)
            ->count();
        $list = GoodsSpecifica::where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()->toArray();
        foreach ($list as &$v) {
            $v['specifica_value'] = json_decode($v['specifica_value'], true);
        }
        unset($v);
        $res = [];
        foreach ($list as $k => $v) {
            $res[$k]['id'] = $v['id'];
            $res[$k]['specifica_name'] = $v['specifica_name'];
            foreach ($v['specifica_value'] as $key => $item) {
                $res[$k]['name'][] = $key;
                $res[$k]['value'][] = implode(array_values($item),'/');

            }
            $res[$k]['name'] = implode($res[$k]['name'],'，');
            $res[$k]['value'] = implode($res[$k]['value'],'，');
//            dd($res[$k]);
        }
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res,
        ];
        return $data;
    }

    public static function speciEdit($post)
    {
        $id = $post['id'];
        unset($post['id']);

        $data = GoodsSpecifica::where('id',$id)->update($post);

        if ($data !== false){
            $res  = [
                'code' => 0,
                'msg' => '修改成功',
                'data' => null
            ];
        }else{
            $re = [
                'code' => 1,
                'msg' => '修改失败',
                'data' => null
            ];
        }
        return $res;
    }
}










